package com.csxy.six.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Component
public class OssUtil {

    private final OSS ossClient;

    @Value("${aliyun.oss.file.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.file.bucketname}")
    private String bucketName;

    @Value("${aliyun.oss.file.folder:avatars}") // 使用默认值 "avatars"
    private String folder;

    public OssUtil(OSS ossClient) {
        this.ossClient = ossClient;
    }

    public String uploadAvatar(MultipartFile file) throws IOException {
        // 检查 OSS 客户端是否初始化
        if (ossClient == null) {
            throw new IllegalStateException("OSS client not initialized. Check your OSS configuration.");
        }

        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = folder + "/" + UUID.randomUUID() + extension;

        PutObjectRequest putObjectRequest =
                new PutObjectRequest(bucketName, fileName, file.getInputStream());
        ossClient.putObject(putObjectRequest);

        return generateObjectUrl(fileName);
    }

    private String generateObjectUrl(String fileName) {
        return "https://" + bucketName + "." + endpoint + "/" + fileName;
    }
}